"""
JH子系统 - 多维度智能匹配引擎
实现语义技能匹配、个性化推荐、AI深度分析等功能
"""

import asyncio
import numpy as np
from typing import Dict, List, Any, Optional, Tuple
from datetime import datetime, timedelta
from dataclasses import dataclass, asdict
from enum import Enum
import json
import re
import math
from pathlib import Path

# 技能级别枚举
class SkillLevel(Enum):
    BEGINNER = "初级"
    INTERMEDIATE = "中级" 
    ADVANCED = "高级"
    EXPERT = "专家"

# 匹配模式枚举
class MatchingMode(Enum):
    EXACT = "精确匹配"
    SEMANTIC = "语义匹配"
    FUZZY = "模糊匹配"
    HYBRID = "混合匹配"

@dataclass
class SkillAssessment:
    """技能评估结果"""
    skill_name: str
    proficiency_level: SkillLevel
    confidence_score: float  # 0-1之间
    market_demand: float    # 市场需求度 0-1
    skill_weight: float     # 技能权重 0-1
    related_skills: List[str]
    evidence_sources: List[str]  # 证据来源

@dataclass
class UserProfile:
    """用户画像"""
    user_id: str
    name: str
    education: Dict[str, Any]
    experience: List[Dict[str, Any]]
    skills: List[SkillAssessment]
    soft_skills: Dict[str, float]  # 软技能评分
    preferences: Dict[str, Any]
    behavioral_data: Dict[str, Any]
    personality_traits: Dict[str, float]
    career_trajectory: List[Dict[str, Any]]

@dataclass
class JobPosition:
    """职位信息"""
    job_id: str
    title: str
    company: str
    description: str
    required_skills: List[Dict[str, Any]]
    preferred_skills: List[Dict[str, Any]]
    soft_skill_requirements: Dict[str, float]
    company_culture: Dict[str, Any]
    compensation: Dict[str, Any]
    location: str
    remote_options: bool
    growth_opportunities: List[str]

@dataclass
class MatchResult:
    """匹配结果"""
    job_id: str
    user_id: str
    overall_score: float
    skill_match_score: float
    culture_match_score: float
    growth_potential_score: float
    salary_match_score: float
    location_match_score: float
    detailed_analysis: Dict[str, Any]
    recommendations: List[str]
    missing_skills: List[str]
    growth_path: List[str]
    confidence_level: float
    match_explanation: str

class SkillSemanticAnalyzer:
    """技能语义分析器"""
    
    def __init__(self):
        self.skill_synonyms = self._load_skill_synonyms()
        self.skill_hierarchy = self._load_skill_hierarchy()
        self.skill_relationships = self._load_skill_relationships()
    
    def _load_skill_synonyms(self) -> Dict[str, List[str]]:
        """加载技能同义词映射"""
        return {
            "python": ["python", "python编程", "python开发", "python语言"],
            "javascript": ["javascript", "js", "前端开发", "网页编程"],
            "machine_learning": ["机器学习", "ml", "人工智能", "ai开发"],
            "project_management": ["项目管理", "项目协调", "团队管理", "敏捷开发"],
            "communication": ["沟通能力", "表达能力", "交流技巧", "口语表达"],
            "leadership": ["领导力", "团队领导", "管理能力", "领导技能"]
        }
    
    def _load_skill_hierarchy(self) -> Dict[str, Dict[str, List[str]]]:
        """加载技能层次结构"""
        return {
            "技术技能": {
                "编程语言": ["Python", "Java", "JavaScript", "C++", "Go"],
                "前端技术": ["React", "Vue", "Angular", "HTML", "CSS"],
                "后端技术": ["Django", "Spring", "Node.js", "FastAPI"],
                "数据库": ["MySQL", "PostgreSQL", "MongoDB", "Redis"],
                "云服务": ["AWS", "Azure", "GCP", "Docker", "Kubernetes"]
            },
            "软技能": {
                "沟通技能": ["口语表达", "书面沟通", "演讲能力", "跨文化交流"],
                "领导技能": ["团队管理", "决策能力", "冲突解决", "战略思维"],
                "协作技能": ["团队合作", "项目协调", "跨部门协作", "敏捷开发"]
            }
        }
    
    def _load_skill_relationships(self) -> Dict[str, List[str]]:
        """加载技能关联关系"""
        return {
            "Python": ["数据科学", "机器学习", "Web开发", "自动化"],
            "React": ["JavaScript", "前端开发", "Web开发", "用户界面"],
            "项目管理": ["团队协作", "沟通能力", "时间管理", "风险控制"]
        }
    
    def analyze_skill_similarity(self, skill1: str, skill2: str) -> float:
        """分析技能相似度"""
        # 直接匹配
        if skill1.lower() == skill2.lower():
            return 1.0
        
        # 同义词匹配
        for canonical, synonyms in self.skill_synonyms.items():
            if skill1.lower() in synonyms and skill2.lower() in synonyms:
                return 0.9
        
        # 层次关系匹配
        similarity_score = self._calculate_hierarchical_similarity(skill1, skill2)
        if similarity_score > 0:
            return similarity_score
        
        # 语义相似度计算（简化版）
        return self._calculate_semantic_similarity(skill1, skill2)
    
    def _calculate_hierarchical_similarity(self, skill1: str, skill2: str) -> float:
        """计算层次相似度"""
        for category, subcategories in self.skill_hierarchy.items():
            for subcat, skills in subcategories.items():
                if skill1 in skills and skill2 in skills:
                    return 0.8  # 同类技能
        return 0.0
    
    def _calculate_semantic_similarity(self, skill1: str, skill2: str) -> float:
        """计算语义相似度（简化实现）"""
        # 这里可以集成更复杂的NLP模型
        common_words = set(skill1.lower().split()) & set(skill2.lower().split())
        if common_words:
            return len(common_words) / max(len(skill1.split()), len(skill2.split())) * 0.6
        return 0.0

class MarketTrendAnalyzer:
    """市场趋势分析器"""
    
    def __init__(self):
        self.skill_demand_trends = self._initialize_skill_trends()
        self.salary_trends = self._initialize_salary_trends()
        self.industry_growth = self._initialize_industry_growth()
    
    def _initialize_skill_trends(self) -> Dict[str, Dict[str, float]]:
        """初始化技能需求趋势"""
        return {
            "Python": {"demand_growth": 0.15, "market_share": 0.25, "future_outlook": 0.9},
            "JavaScript": {"demand_growth": 0.12, "market_share": 0.30, "future_outlook": 0.85},
            "机器学习": {"demand_growth": 0.25, "market_share": 0.15, "future_outlook": 0.95},
            "云计算": {"demand_growth": 0.20, "market_share": 0.20, "future_outlook": 0.90},
            "数据分析": {"demand_growth": 0.18, "market_share": 0.22, "future_outlook": 0.88}
        }
    
    def _initialize_salary_trends(self) -> Dict[str, Dict[str, float]]:
        """初始化薪资趋势"""
        return {
            "Python": {"avg_salary": 120000, "salary_growth": 0.08, "premium": 1.2},
            "机器学习": {"avg_salary": 140000, "salary_growth": 0.12, "premium": 1.4},
            "云计算": {"avg_salary": 130000, "salary_growth": 0.10, "premium": 1.3}
        }
    
    def _initialize_industry_growth(self) -> Dict[str, float]:
        """初始化行业增长率"""
        return {
            "人工智能": 0.22,
            "云计算": 0.18,
            "数据科学": 0.20,
            "网络安全": 0.15,
            "金融科技": 0.16
        }
    
    def get_skill_market_value(self, skill: str) -> Dict[str, float]:
        """获取技能市场价值"""
        trend_data = self.skill_demand_trends.get(skill, {
            "demand_growth": 0.05,
            "market_share": 0.10,
            "future_outlook": 0.70
        })
        
        salary_data = self.salary_trends.get(skill, {
            "avg_salary": 90000,
            "salary_growth": 0.05,
            "premium": 1.0
        })
        
        return {
            "market_demand": trend_data["demand_growth"],
            "growth_potential": trend_data["future_outlook"],
            "salary_premium": salary_data["premium"],
            "competitiveness": trend_data["market_share"]
        }

class PersonalityMatcher:
    """个性特质匹配器"""
    
    def __init__(self):
        self.personality_weights = {
            "openness": 0.2,
            "conscientiousness": 0.25,
            "extraversion": 0.2,
            "agreeableness": 0.15,
            "neuroticism": 0.1,
            "adaptability": 0.1
        }
    
    def match_personality_to_role(self, user_traits: Dict[str, float], 
                                 role_requirements: Dict[str, float]) -> float:
        """匹配个性特质与角色要求"""
        total_score = 0.0
        
        for trait, user_value in user_traits.items():
            if trait in role_requirements:
                required_value = role_requirements[trait]
                weight = self.personality_weights.get(trait, 0.1)
                
                # 计算匹配度（避免过度惩罚）
                diff = abs(user_value - required_value)
                score = max(0, 1 - diff) * weight
                total_score += score
        
        return min(total_score, 1.0)

class IntelligentMatchingEngine:
    """智能匹配引擎主类"""
    
    def __init__(self):
        self.skill_analyzer = SkillSemanticAnalyzer()
        self.market_analyzer = MarketTrendAnalyzer()
        self.personality_matcher = PersonalityMatcher()
        self.user_behavior_history = {}
        self.matching_history = {}
    
    async def comprehensive_matching(self, user_profile: UserProfile, 
                                   job_positions: List[JobPosition],
                                   matching_mode: MatchingMode = MatchingMode.HYBRID) -> List[MatchResult]:
        """综合匹配分析"""
        results = []
        
        for job in job_positions:
            # 1. 多维度评分
            skill_score = await self._calculate_skill_match_score(user_profile, job)
            culture_score = self._calculate_culture_match_score(user_profile, job)
            growth_score = self._calculate_growth_potential_score(user_profile, job)
            salary_score = self._calculate_salary_match_score(user_profile, job)
            location_score = self._calculate_location_match_score(user_profile, job)
            
            # 2. 综合评分计算
            weights = {
                "skill": 0.35,
                "culture": 0.20,
                "growth": 0.20,
                "salary": 0.15,
                "location": 0.10
            }
            
            overall_score = (
                skill_score * weights["skill"] +
                culture_score * weights["culture"] +
                growth_score * weights["growth"] +
                salary_score * weights["salary"] +
                location_score * weights["location"]
            )
            
            # 3. 生成详细分析
            detailed_analysis = await self._generate_detailed_analysis(
                user_profile, job, skill_score, culture_score, growth_score
            )
            
            # 4. 生成推荐建议
            recommendations = self._generate_recommendations(user_profile, job, detailed_analysis)
            
            # 5. 识别缺失技能
            missing_skills = self._identify_missing_skills(user_profile, job)
            
            # 6. 生成成长路径
            growth_path = self._generate_growth_path(user_profile, job)
            
            # 7. 计算置信度
            confidence = self._calculate_confidence_level(detailed_analysis)
            
            # 8. 生成匹配解释
            explanation = self._generate_match_explanation(
                overall_score, skill_score, culture_score, growth_score
            )
            
            result = MatchResult(
                job_id=job.job_id,
                user_id=user_profile.user_id,
                overall_score=overall_score,
                skill_match_score=skill_score,
                culture_match_score=culture_score,
                growth_potential_score=growth_score,
                salary_match_score=salary_score,
                location_match_score=location_score,
                detailed_analysis=detailed_analysis,
                recommendations=recommendations,
                missing_skills=missing_skills,
                growth_path=growth_path,
                confidence_level=confidence,
                match_explanation=explanation
            )
            
            results.append(result)
        
        # 按综合得分排序
        results.sort(key=lambda x: x.overall_score, reverse=True)
        
        # 更新用户行为历史
        await self._update_user_behavior(user_profile.user_id, results)
        
        return results
    
    async def _calculate_skill_match_score(self, user_profile: UserProfile, 
                                         job: JobPosition) -> float:
        """计算技能匹配分数"""
        user_skills = {skill.skill_name: skill for skill in user_profile.skills}
        required_skills = job.required_skills
        preferred_skills = job.preferred_skills
        
        total_score = 0.0
        max_possible_score = 0.0
        
        # 必需技能匹配（权重更高）
        for req_skill in required_skills:
            skill_name = req_skill.get("name", "")
            required_level = req_skill.get("level", "中级")
            weight = req_skill.get("weight", 1.0) * 1.5  # 必需技能权重加倍
            
            max_possible_score += weight
            
            best_match = 0.0
            for user_skill_name, user_skill in user_skills.items():
                similarity = self.skill_analyzer.analyze_skill_similarity(
                    user_skill_name, skill_name
                )
                
                if similarity > 0.7:  # 高相似度才考虑
                    # 技能水平匹配度
                    level_match = self._calculate_skill_level_match(
                        user_skill.proficiency_level.value, required_level
                    )
                    
                    # 市场价值加权
                    market_value = self.market_analyzer.get_skill_market_value(skill_name)
                    market_bonus = market_value["market_demand"] * 0.1
                    
                    skill_score = (similarity * level_match + market_bonus) * weight
                    best_match = max(best_match, skill_score)
            
            total_score += best_match
        
        # 优选技能匹配
        for pref_skill in preferred_skills:
            skill_name = pref_skill.get("name", "")
            weight = pref_skill.get("weight", 0.5)
            
            max_possible_score += weight
            
            best_match = 0.0
            for user_skill_name, user_skill in user_skills.items():
                similarity = self.skill_analyzer.analyze_skill_similarity(
                    user_skill_name, skill_name
                )
                
                if similarity > 0.6:
                    skill_score = similarity * weight
                    best_match = max(best_match, skill_score)
            
            total_score += best_match
        
        return min(total_score / max_possible_score if max_possible_score > 0 else 0, 1.0)
    
    def _calculate_skill_level_match(self, user_level: str, required_level: str) -> float:
        """计算技能水平匹配度"""
        level_mapping = {"初级": 1, "中级": 2, "高级": 3, "专家": 4}
        
        user_score = level_mapping.get(user_level, 2)
        required_score = level_mapping.get(required_level, 2)
        
        if user_score >= required_score:
            return 1.0
        else:
            return user_score / required_score * 0.8  # 水平不足的惩罚
    
    def _calculate_culture_match_score(self, user_profile: UserProfile, 
                                     job: JobPosition) -> float:
        """计算企业文化匹配分数"""
        user_traits = user_profile.personality_traits
        company_culture = job.company_culture
        
        culture_score = self.personality_matcher.match_personality_to_role(
            user_traits, company_culture.get("personality_requirements", {})
        )
        
        # 工作环境偏好匹配
        work_preferences = user_profile.preferences.get("work_environment", {})
        company_environment = company_culture.get("work_environment", {})
        
        env_score = 0.0
        for pref, user_value in work_preferences.items():
            if pref in company_environment:
                company_value = company_environment[pref]
                env_score += 1 - abs(user_value - company_value)
        
        env_score = env_score / len(work_preferences) if work_preferences else 0.5
        
        return (culture_score * 0.7 + env_score * 0.3)
    
    def _calculate_growth_potential_score(self, user_profile: UserProfile, 
                                        job: JobPosition) -> float:
        """计算成长潜力分数"""
        # 分析用户的学习轨迹
        learning_velocity = self._analyze_learning_velocity(user_profile)
        
        # 分析职位提供的成长机会
        growth_opportunities = job.growth_opportunities
        
        # 技能发展路径匹配
        skill_development_match = self._calculate_skill_development_match(
            user_profile, growth_opportunities
        )
        
        # 行业发展前景
        industry_growth = self.market_analyzer.industry_growth.get(
            job.company, 0.10
        )
        
        return (
            learning_velocity * 0.4 +
            skill_development_match * 0.4 +
            industry_growth * 0.2
        )
    
    def _analyze_learning_velocity(self, user_profile: UserProfile) -> float:
        """分析学习速度"""
        career_trajectory = user_profile.career_trajectory
        
        if len(career_trajectory) < 2:
            return 0.7  # 默认值
        
        skill_growth = 0.0
        time_span = 0
        
        for i in range(1, len(career_trajectory)):
            prev_position = career_trajectory[i-1]
            curr_position = career_trajectory[i]
            
            # 计算技能增长
            prev_skills = set(prev_position.get("skills", []))
            curr_skills = set(curr_position.get("skills", []))
            new_skills = curr_skills - prev_skills
            
            # 计算时间跨度
            prev_date = datetime.fromisoformat(prev_position.get("end_date", "2020-01-01"))
            curr_date = datetime.fromisoformat(curr_position.get("start_date", "2021-01-01"))
            time_diff = (curr_date - prev_date).days
            
            if time_diff > 0:
                skill_growth += len(new_skills) / (time_diff / 365)
                time_span += time_diff / 365
        
        if time_span > 0:
            learning_rate = skill_growth / time_span
            return min(learning_rate / 3.0, 1.0)  # 归一化到0-1
        
        return 0.7
    
    def _calculate_skill_development_match(self, user_profile: UserProfile, 
                                         growth_opportunities: List[str]) -> float:
        """计算技能发展匹配度"""
        user_interests = user_profile.preferences.get("skill_interests", [])
        
        if not user_interests or not growth_opportunities:
            return 0.5
        
        matches = 0
        for opportunity in growth_opportunities:
            for interest in user_interests:
                similarity = self.skill_analyzer.analyze_skill_similarity(
                    opportunity, interest
                )
                if similarity > 0.6:
                    matches += similarity
                    break
        
        return min(matches / len(growth_opportunities), 1.0)
    
    def _calculate_salary_match_score(self, user_profile: UserProfile, 
                                    job: JobPosition) -> float:
        """计算薪资匹配分数"""
        user_expectations = user_profile.preferences.get("salary_expectations", {})
        job_compensation = job.compensation
        
        min_expected = user_expectations.get("min", 60000)
        max_expected = user_expectations.get("max", 200000)
        preferred = user_expectations.get("preferred", 100000)
        
        offered_min = job_compensation.get("min", 80000)
        offered_max = job_compensation.get("max", 120000)
        offered_avg = (offered_min + offered_max) / 2
        
        # 基础匹配分数
        if offered_avg >= preferred:
            base_score = 1.0
        elif offered_avg >= min_expected:
            base_score = 0.7 + 0.3 * (offered_avg - min_expected) / (preferred - min_expected)
        else:
            base_score = 0.3 * offered_avg / min_expected
        
        # 考虑其他福利
        benefits_score = self._calculate_benefits_score(
            user_profile.preferences.get("benefits", {}),
            job_compensation.get("benefits", {})
        )
        
        return min(base_score * 0.8 + benefits_score * 0.2, 1.0)
    
    def _calculate_benefits_score(self, user_benefits: Dict[str, Any], 
                                job_benefits: Dict[str, Any]) -> float:
        """计算福利匹配分数"""
        if not user_benefits:
            return 0.7
        
        total_score = 0.0
        total_weight = 0.0
        
        for benefit, importance in user_benefits.items():
            total_weight += importance
            if benefit in job_benefits and job_benefits[benefit]:
                total_score += importance
        
        return total_score / total_weight if total_weight > 0 else 0.7
    
    def _calculate_location_match_score(self, user_profile: UserProfile, 
                                      job: JobPosition) -> float:
        """计算地理位置匹配分数"""
        user_location_pref = user_profile.preferences.get("location", {})
        
        # 远程工作偏好
        remote_preference = user_location_pref.get("remote_preference", 0.5)
        if job.remote_options and remote_preference > 0.7:
            return 1.0
        
        # 地理位置匹配
        preferred_locations = user_location_pref.get("preferred_cities", [])
        if not preferred_locations:
            return 0.8  # 默认分数
        
        job_location = job.location.lower()
        for pref_location in preferred_locations:
            if pref_location.lower() in job_location or job_location in pref_location.lower():
                return 1.0
        
        # 通勤距离考虑（简化处理）
        return 0.6 if not job.remote_options else 0.8
    
    async def _generate_detailed_analysis(self, user_profile: UserProfile,
                                        job: JobPosition, skill_score: float,
                                        culture_score: float, growth_score: float) -> Dict[str, Any]:
        """生成详细分析报告"""
        return {
            "skill_analysis": {
                "matching_skills": self._get_matching_skills(user_profile, job),
                "skill_gaps": self._identify_skill_gaps(user_profile, job),
                "skill_level_assessment": self._assess_skill_levels(user_profile, job)
            },
            "cultural_fit": {
                "personality_match": culture_score,
                "work_style_compatibility": self._analyze_work_style_compatibility(user_profile, job),
                "team_fit_prediction": self._predict_team_fit(user_profile, job)
            },
            "growth_analysis": {
                "learning_potential": growth_score,
                "career_trajectory_alignment": self._analyze_career_alignment(user_profile, job),
                "skill_development_opportunities": job.growth_opportunities
            },
            "risk_assessment": {
                "retention_probability": self._calculate_retention_probability(user_profile, job),
                "performance_prediction": self._predict_performance(user_profile, job)
            }
        }
    
    def _get_matching_skills(self, user_profile: UserProfile, job: JobPosition) -> List[Dict[str, Any]]:
        """获取匹配的技能"""
        matching_skills = []
        user_skills = {skill.skill_name: skill for skill in user_profile.skills}
        
        for req_skill in job.required_skills:
            skill_name = req_skill.get("name", "")
            
            for user_skill_name, user_skill in user_skills.items():
                similarity = self.skill_analyzer.analyze_skill_similarity(
                    user_skill_name, skill_name
                )
                
                if similarity > 0.7:
                    matching_skills.append({
                        "user_skill": user_skill_name,
                        "required_skill": skill_name,
                        "similarity": similarity,
                        "user_level": user_skill.proficiency_level.value,
                        "required_level": req_skill.get("level", "中级")
                    })
        
        return matching_skills
    
    def _identify_skill_gaps(self, user_profile: UserProfile, job: JobPosition) -> List[str]:
        """识别技能差距"""
        user_skills = {skill.skill_name.lower() for skill in user_profile.skills}
        gaps = []
        
        for req_skill in job.required_skills:
            skill_name = req_skill.get("name", "").lower()
            
            # 检查是否有相似技能
            has_similar = any(
                self.skill_analyzer.analyze_skill_similarity(user_skill, skill_name) > 0.6
                for user_skill in user_skills
            )
            
            if not has_similar:
                gaps.append(req_skill.get("name", ""))
        
        return gaps
    
    def _assess_skill_levels(self, user_profile: UserProfile, job: JobPosition) -> Dict[str, Any]:
        """评估技能水平"""
        assessment = {
            "above_requirement": [],
            "meets_requirement": [],
            "below_requirement": []
        }
        
        user_skills = {skill.skill_name: skill for skill in user_profile.skills}
        
        for req_skill in job.required_skills:
            skill_name = req_skill.get("name", "")
            required_level = req_skill.get("level", "中级")
            
            for user_skill_name, user_skill in user_skills.items():
                similarity = self.skill_analyzer.analyze_skill_similarity(
                    user_skill_name, skill_name
                )
                
                if similarity > 0.7:
                    level_match = self._calculate_skill_level_match(
                        user_skill.proficiency_level.value, required_level
                    )
                    
                    if level_match >= 1.0:
                        assessment["above_requirement"].append(skill_name)
                    elif level_match >= 0.8:
                        assessment["meets_requirement"].append(skill_name)
                    else:
                        assessment["below_requirement"].append(skill_name)
        
        return assessment
    
    def _analyze_work_style_compatibility(self, user_profile: UserProfile, 
                                        job: JobPosition) -> Dict[str, float]:
        """分析工作风格兼容性"""
        user_work_style = user_profile.preferences.get("work_style", {})
        company_culture = job.company_culture.get("work_style", {})
        
        compatibility = {}
        
        for aspect, user_pref in user_work_style.items():
            if aspect in company_culture:
                company_pref = company_culture[aspect]
                compatibility[aspect] = 1 - abs(user_pref - company_pref)
            else:
                compatibility[aspect] = 0.5  # 中性分数
        
        return compatibility
    
    def _predict_team_fit(self, user_profile: UserProfile, job: JobPosition) -> float:
        """预测团队适配性"""
        user_traits = user_profile.personality_traits
        team_requirements = job.company_culture.get("team_dynamics", {})
        
        return self.personality_matcher.match_personality_to_role(
            user_traits, team_requirements
        )
    
    def _analyze_career_alignment(self, user_profile: UserProfile, job: JobPosition) -> float:
        """分析职业轨迹对齐度"""
        career_goals = user_profile.preferences.get("career_goals", [])
        job_growth_opportunities = job.growth_opportunities
        
        if not career_goals:
            return 0.7
        
        alignment_score = 0.0
        for goal in career_goals:
            best_match = max(
                (self.skill_analyzer.analyze_skill_similarity(goal, opportunity)
                 for opportunity in job_growth_opportunities),
                default=0.0
            )
            alignment_score += best_match
        
        return alignment_score / len(career_goals)
    
    def _calculate_retention_probability(self, user_profile: UserProfile, 
                                       job: JobPosition) -> float:
        """计算留任概率"""
        # 基于多个因素计算留任概率
        factors = {
            "career_fit": self._analyze_career_alignment(user_profile, job) * 0.3,
            "culture_fit": self._calculate_culture_match_score(user_profile, job) * 0.25,
            "growth_potential": self._calculate_growth_potential_score(user_profile, job) * 0.25,
            "compensation_satisfaction": self._calculate_salary_match_score(user_profile, job) * 0.2
        }
        
        return sum(factors.values())
    
    def _predict_performance(self, user_profile: UserProfile, job: JobPosition) -> float:
        """预测工作表现"""
        skill_score = 0.0
        user_skills = {skill.skill_name: skill for skill in user_profile.skills}
        
        # 基于技能匹配度和经验预测表现
        for req_skill in job.required_skills:
            skill_name = req_skill.get("name", "")
            
            for user_skill_name, user_skill in user_skills.items():
                similarity = self.skill_analyzer.analyze_skill_similarity(
                    user_skill_name, skill_name
                )
                
                if similarity > 0.7:
                    # 考虑技能水平和置信度
                    level_bonus = {
                        "初级": 0.6, "中级": 0.8, "高级": 1.0, "专家": 1.2
                    }.get(user_skill.proficiency_level.value, 0.8)
                    
                    skill_score += similarity * level_bonus * user_skill.confidence_score
        
        # 归一化
        max_possible_score = len(job.required_skills) * 1.2
        normalized_score = skill_score / max_possible_score if max_possible_score > 0 else 0
        
        return min(normalized_score, 1.0)
    
    def _generate_recommendations(self, user_profile: UserProfile, 
                                job: JobPosition, detailed_analysis: Dict[str, Any]) -> List[str]:
        """生成推荐建议"""
        recommendations = []
        
        # 基于技能差距的建议
        skill_gaps = detailed_analysis["skill_analysis"]["skill_gaps"]
        if skill_gaps:
            recommendations.append(f"建议加强以下技能：{', '.join(skill_gaps[:3])}")
        
        # 基于技能水平的建议
        below_req = detailed_analysis["skill_analysis"]["skill_level_assessment"]["below_requirement"]
        if below_req:
            recommendations.append(f"需要提升以下技能水平：{', '.join(below_req[:2])}")
        
        # 基于文化匹配的建议
        culture_score = detailed_analysis["cultural_fit"]["personality_match"]
        if culture_score < 0.7:
            recommendations.append("建议了解公司文化，评估个人适配性")
        
        # 基于成长潜力的建议
        growth_score = detailed_analysis["growth_analysis"]["learning_potential"]
        if growth_score > 0.8:
            recommendations.append("您的学习能力强，这个职位有很好的发展前景")
        
        return recommendations
    
    def _identify_missing_skills(self, user_profile: UserProfile, job: JobPosition) -> List[str]:
        """识别缺失技能"""
        return self._identify_skill_gaps(user_profile, job)
    
    def _generate_growth_path(self, user_profile: UserProfile, job: JobPosition) -> List[str]:
        """生成成长路径"""
        growth_path = []
        
        # 基于职位要求和用户技能生成学习路径
        skill_gaps = self._identify_skill_gaps(user_profile, job)
        
        for skill in skill_gaps[:3]:  # 优先处理前3个技能
            # 查找相关技能
            related_skills = self.skill_analyzer.skill_relationships.get(skill, [])
            
            if related_skills:
                growth_path.append(f"学习 {skill}（建议先掌握：{related_skills[0]}）")
            else:
                growth_path.append(f"学习 {skill}")
        
        # 添加软技能发展建议
        soft_skill_gaps = []
        user_soft_skills = user_profile.soft_skills
        required_soft_skills = job.soft_skill_requirements
        
        for skill, required_level in required_soft_skills.items():
            user_level = user_soft_skills.get(skill, 0.5)
            if user_level < required_level:
                soft_skill_gaps.append(skill)
        
        if soft_skill_gaps:
            growth_path.append(f"提升软技能：{', '.join(soft_skill_gaps[:2])}")
        
        return growth_path
    
    def _calculate_confidence_level(self, detailed_analysis: Dict[str, Any]) -> float:
        """计算置信度"""
        # 基于分析的完整性和一致性计算置信度
        factors = [
            len(detailed_analysis["skill_analysis"]["matching_skills"]) > 0,
            detailed_analysis["cultural_fit"]["personality_match"] > 0.5,
            detailed_analysis["growth_analysis"]["learning_potential"] > 0.3,
            detailed_analysis["risk_assessment"]["retention_probability"] > 0.4
        ]
        
        base_confidence = sum(factors) / len(factors)
        
        # 考虑数据质量
        data_quality = min(1.0, len(detailed_analysis) / 4.0)
        
        return base_confidence * data_quality
    
    def _generate_match_explanation(self, overall_score: float, skill_score: float,
                                  culture_score: float, growth_score: float) -> str:
        """生成匹配解释"""
        if overall_score >= 0.85:
            return f"高度匹配：技能匹配度{skill_score:.1%}，文化适配度{culture_score:.1%}，成长潜力{growth_score:.1%}"
        elif overall_score >= 0.70:
            return f"良好匹配：总体评分{overall_score:.1%}，建议重点关注技能提升"
        elif overall_score >= 0.55:
            return f"中等匹配：有一定潜力，需要时间适应和学习"
        else:
            return f"匹配度较低：建议考虑其他更适合的职位机会"
    
    async def _update_user_behavior(self, user_id: str, match_results: List[MatchResult]):
        """更新用户行为历史"""
        if user_id not in self.user_behavior_history:
            self.user_behavior_history[user_id] = []
        
        # 记录匹配会话
        session = {
            "timestamp": datetime.now().isoformat(),
            "match_count": len(match_results),
            "top_scores": [r.overall_score for r in match_results[:5]],
            "job_categories": list(set(r.job_id.split("_")[0] for r in match_results))
        }
        
        self.user_behavior_history[user_id].append(session)
        
        # 保持历史记录在合理范围内
        if len(self.user_behavior_history[user_id]) > 50:
            self.user_behavior_history[user_id] = self.user_behavior_history[user_id][-50:]
    
    async def fuzzy_matching(self, user_query: str, job_positions: List[JobPosition]) -> List[MatchResult]:
        """模糊匹配：处理用户不明确需求"""
        # 解析用户模糊需求
        parsed_requirements = await self._parse_fuzzy_query(user_query)
        
        # 创建临时用户画像
        temp_profile = self._create_temp_profile_from_query(parsed_requirements)
        
        # 执行匹配
        results = await self.comprehensive_matching(temp_profile, job_positions, MatchingMode.FUZZY)
        
        # 调整匹配结果以适应模糊查询
        adjusted_results = self._adjust_fuzzy_results(results, parsed_requirements)
        
        return adjusted_results
    
    async def _parse_fuzzy_query(self, query: str) -> Dict[str, Any]:
        """解析模糊查询"""
        # 简化的NLP解析
        keywords = {
            "技能": ["python", "java", "机器学习", "数据分析", "前端", "后端"],
            "位置": ["北京", "上海", "深圳", "杭州", "远程"],
            "薪资": ["高薪", "薪资", "收入", "待遇"],
            "公司": ["大厂", "初创", "外企", "国企"],
            "工作性质": ["全职", "兼职", "实习", "远程"]
        }
        
        parsed = {
            "skills": [],
            "location": [],
            "salary_preference": "medium",
            "company_type": [],
            "work_type": "全职"
        }
        
        query_lower = query.lower()
        
        for category, terms in keywords.items():
            for term in terms:
                if term in query_lower:
                    if category == "技能":
                        parsed["skills"].append(term)
                    elif category == "位置":
                        parsed["location"].append(term)
                    elif category == "薪资":
                        parsed["salary_preference"] = "high"
                    elif category == "公司":
                        parsed["company_type"].append(term)
                    elif category == "工作性质":
                        parsed["work_type"] = term
        
        return parsed
    
    def _create_temp_profile_from_query(self, requirements: Dict[str, Any]) -> UserProfile:
        """从查询需求创建临时用户画像"""
        skills = []
        for skill_name in requirements.get("skills", []):
            skill = SkillAssessment(
                skill_name=skill_name,
                proficiency_level=SkillLevel.INTERMEDIATE,
                confidence_score=0.7,
                market_demand=0.8,
                skill_weight=0.8,
                related_skills=[],
                evidence_sources=["用户查询"]
            )
            skills.append(skill)
        
        preferences = {
            "location": {"preferred_cities": requirements.get("location", [])},
            "salary_expectations": {
                "min": 80000 if requirements.get("salary_preference") == "high" else 60000,
                "preferred": 120000 if requirements.get("salary_preference") == "high" else 90000,
                "max": 200000 if requirements.get("salary_preference") == "high" else 150000
            },
            "work_style": {},
            "company_type": requirements.get("company_type", [])
        }
        
        return UserProfile(
            user_id="temp_user",
            name="临时用户",
            education={},
            experience=[],
            skills=skills,
            soft_skills={"沟通能力": 0.7, "团队协作": 0.7, "学习能力": 0.8},
            preferences=preferences,
            behavioral_data={},
            personality_traits={"openness": 0.7, "conscientiousness": 0.7},
            career_trajectory=[]
        )
    
    def _adjust_fuzzy_results(self, results: List[MatchResult], 
                            requirements: Dict[str, Any]) -> List[MatchResult]:
        """调整模糊匹配结果"""
        # 对于模糊查询，降低置信度要求，增加多样性
        for result in results:
            # 模糊匹配的置信度调整
            result.confidence_level *= 0.8
            
            # 添加模糊匹配说明
            result.match_explanation = f"基于模糊需求匹配：{result.match_explanation}"
            
            # 增加探索性推荐
            result.recommendations.insert(0, "这是基于您的模糊需求的推荐，建议详细了解职位详情")
        
        return results


# 智能匹配引擎全局实例
intelligent_matching_engine = IntelligentMatchingEngine() 